package server;

import java.io.IOException;
import java.util.Scanner;

import client.ClientMain;
import server.ServerMain;
import init.InitMeasurements;
import init.InitAps;

public class Main {
    static boolean launched = false;

	public static String getInput(){

	    Scanner in = new Scanner(System.in);
	    String choice = in.next();
	    return choice;
	}
	
    public static void main(String[] args) throws IOException {
	    Oserver rserver  = new Oserver();
	    
	    Runtime.getRuntime().addShutdownHook(new Thread(){
		    public void run() {
		    	if ( launched) {
		    		ServerMain.closesocket();
		    	}
		    	System.out.println("Close") ;
		  }
		 });
	    
	    
	    boolean state = true;
	    while(state){
			System.out.println("############## MENU ##############") ;
		    System.out.println("Take one option :") ;
		    System.out.println("1 - Change the UDP port ( Current " + Oserver.getPort()+ ")" ) ;
		    System.out.println("2 - Load new Access point ") ;
		    System.out.println("3 - Load new data for map in the database ") ;
		    System.out.println("4 - Launch the server") ;
		    System.out.println("8 - Launch the client test") ;
		    System.out.println("9 - Quitter") ;
		    
		    String choice = getInput() ;
		
		    if (choice.compareTo("1") == 0){
		    
		    	System.out.println("<<<< Put the new UDP port.");
			    String port = getInput() ;
			    Oserver.setPort(Integer.parseInt(port));
		    
		    }else if  ( choice.compareTo("2") == 0){

		    	System.out.println("<<<< Put the link of the new Aps.cfg file.");
			    String link1 = getInput() ;
		    	InitAps.addAps(link1);
		    
		    }else if  ( choice.compareTo("3") == 0){
	        
		    	System.out.println("<<<< Put the link of the database csv file.");
			    String link2 = getInput() ;
		    	InitMeasurements.addMeasurements(link2);

		    }else if  ( choice.compareTo("4") == 0){
		 
		    	new ServerMain(rserver)	;
		    	launched = true;
		        ServerMain.launchdatabase();
		        try {
		        	ServerMain.launchserver(Oserver.getPort(), Oserver.getInetAddress());
				} catch (IOException e) {
					e.printStackTrace();
		            System.out.println("Error : Serveur cannot be launched from the main !");
		            System.exit(-1);
				}
		    }else if  ( choice.compareTo("8") == 0){
		    	ClientMain.main(args);
			}else if  ( choice.compareTo("9") == 0){
		    	state=false;    
		    }
	    }
    }
}
